from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User,Goods
from myapp.myser import *
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket

import uuid

# 导入数据库模型类

# 手写md5加密方法
def make_password(mypass):
    #生成md5对象
    md5 = hashlib.md5()
    # 定义加密对象
    sign_str = mypass
    # 转码
    sign_utf8 = str(sign_str).encode(encoding='utf-8')
    # 加密操作
    md5.update(sign_utf8)
    # 生成密文
    md5_server = md5.hexdigest()
    # 返回最终数据
    return md5_server


# 注册接口
class Register(APIView):
    
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', '未收到用户名')
        password = request.GET.get('password', '未收到密码')
        code = request.GET.get('code', '未收到密码')
        # 从redis获取生成好的验证码
        # mycode = r.get('code').decode('utf-8')
        # 从session获取验证码
        mycode1 = request.session.get('code', None)
        if code != mycode1:
            res = {}
            res['code'] = 405
            res['message'] = '验证码错误'
            return Response(res)
        
        # 判断有没有重名用户
        user = User.objects.filter(username=username).first()
        if user:
            # 该用户已存在
            res = {}
            res['code'] = 405
            res['message'] = '用户已经存在'
            return Response(res)
        # 进行数据入库
        user = User(
            username=username,
            password=make_password(password),
            img='',
            type=0
        )
        user.save()
        # 返回结果
        res = {}
        res['code'] = 200
        res['message'] = '注册成功'
        return Response(res)
    
# 验证码生成链接
# 导入随机函数
class Register_code(APIView):
    
    def get(self, request):
        import random
        checkcode=''
        for i in range(4):
            current=random.randrange(0,4)   #生成随机数与循环次数比对
            current1 = random.randrange(0,4)
            if current == i:
                tmp=chr(random.randint(65,90))   #65~90为ASCii码表A~Z
            elif current1 == i:
                tmp = chr(random.randint(97,122))   #97~122为ASCii码表a~z
            else:
                tmp=random.randint(0,9)
            checkcode+=str(tmp)
        res = {}
        res['code'] = 200
        res['message'] = checkcode
        print(res)
        return Response(res)
    
# 定义图片验证码 
r = redis.Redis()
class MyCode(View):
    
    # 定义随即验证颜色
    def ger_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)
        
        return (R, G, B)
    # 随机验证码
    def get(self, request):
        # 画布
        img_size = (110, 50)
        # 定义颜色
        image = Image.new('RGB', img_size, 'white')
        # 为这张画布定义画笔对象
        draw = ImageDraw.Draw(image, 'RGB')
        # 定义随即字符串
        source = '0123456789'
        # 定义容器接受随机字符串
        code_str = ''
        for i in range(4):
            # 获取字体颜色
            text_color = self.ger_random_color()
            # 获取字符串
            tmp_num = random.randrange(len(source))
            # 获取字符集
            random_str = source[tmp_num]
            # 添加到容器中
            code_str += random_str
            # 绘制
            draw.text((10+30*i,20), random_str, text_color)
        # 文件流缓冲区
        buf = io.BytesIO()
        # 将图片保存到缓冲区
        image.save(buf, 'png')
        # 将随机验证码存储到redis中
        r.set('code', code_str)
        # 将随机验证码存储到session中
        request.session['code'] = code_str
        # print(request.session.get('code'))
        return HttpResponse(buf.getvalue(), 'image/png')
    
    
# 登录接口
class LognIn(APIView):
    def get(self, request):
        # 获取账户名和密码
        username = request.GET.get('username')
        password = request.GET.get('password')
        # code = request.GET.get('code')
        # mycode = r.get('code').decode('utf-8')
        # mycode = mycode.decode('utf-8')
        # print(mycode)
        # mycode = request.session.get('code', None)
        # if code != mycode:
        #     res = {}
        #     res['code'] = 405
        #     res['message'] = '验证码错误'
        #     return Response(res)
        user = User.objects.filter(username=username,password=make_password(password)).first()
        if user:
            res = {}
            res['code'] = 200
            res['message'] = '登陆成功'
            res['username'] = username
            res['uid'] = user.id
            encode_jwt = jwt.encode({'uid': str(user.id)}, '446652', algorithm='HS256')

            encode_str = str(encode_jwt, 'utf-8')
            res['jwt'] = encode_str
            
            return Response(res)
        res = {}
        res['code'] = 405
        res['message'] = '账号或密码错误,请重新输入!'
        return Response(res)
    




class weibo_back(APIView):
    def get(self, request):
        #获取code
        code = request.GET.get('code')

        #换取网址
        access_token_url = "https://api.weibo.com/oauth2/access_token"

        #发送请求进行换取
        re_dict = requests.post(
            access_token_url,
            data={
            "client_id": '2636039333',
            "client_secret": "4e2fbdb39432c31dc5c2f90be3afa5ce",
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": "http://127.0.0.1:8000/md_admin/weibo"
            }
        )
        uid = json.loads(re_dict.text)['uid']
        # 判断是否使用过新浪登录
        user = User.objects.filter(username=str(uid)).first()
        
        sina_id = ''
        user_id = ''
        if user:
            # 登陆过
            sina_id = user.username
            user_id = user.id
        else:
            # 自动创建账号
            user = User(username=str(uid),password='',type=0)
            # 保存
            user.save()
            # 查询用户id
            user = User.objects.filter(username=str(uid)).first()
            
            sina_id = str(uid)
            user_id = user.id
        print(sina_id)
        print(user_id)
        r.set('sinaUid', str(uid))
        return HttpResponseRedirect("http://127.0.0.1:8080/weibo")
class mounted(APIView):
    def get(self, request):
        uid = r.get('sinaUid').decode('utf-8')
        res = {}
        user = User.objects.filter(username=uid).first()
        if user:
            res['code'] = 200
            res['message'] = '第三方登录成功'
            res['username'] = user.username
            res['uid'] = user.id
        else:
            res['code'] = 405
            res['message'] = '未进行第三方登录'
        return Response(res)
    
import time
import hmac
import base64
from hashlib import sha256
import urllib
import json

#构造钉钉回调方法
def ding_back(request):
    
    #获取code
    code = request.GET.get("code")

    t = time.time()
    #时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret ='ly-AzMKMmCKQP3geaILT_An32kEfKO3HeOtApy5CgKwjytevVZC0WYsT2gxMB160'
    #构造签名
    signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'), digestmod=sha256).digest())
    #请求接口，换取钉钉用户名
    payload = {'tmp_auth_code':code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='+urllib.parse.quote(signature.decode("utf-8"))+"&timestamp="+timestamp+"&accessKey=dingoaukgkwqknzjvamdqh",data=json.dumps(payload),headers=headers)

    res_dict = json.loads(res.text)
    print(res_dict)
    username = res_dict['user_info']['nick']
    user = User.objects.filter(username=username).first() 
    dingding_id = ''
    user_id = ''
    if user:
        # 登陆过
        dingding_id = user.username
        user_id = user.id
    else:
        # 自动创建账号
        user = User(username=username,password='',type=0)
        # 保存
        user.save()
        # 查询用户id
        user = User.objects.filter(username=username).first()
        
        dingding_id = username
        user_id = user.id
        
    return redirect('http://127.0.0.1:8080?dingding_id=' + dingding_id + '&uid=' + str(user_id))


# 导入上传路径
from mydjango.settings import UPLOAD_ROOT
# 定义一个上传文件类
class UploadFile(APIView):
    # 定义post方法
    def post(self, request):
        # 接收文件
        my_file = request.FILES.get('file')
        print(my_file)
        # print(my_file.name)
        uploadroot = os.path.join(UPLOAD_ROOT).replace('\\','/')
        
        # f = open(uploadroot + '/' + my_file.name, 'w')
        # for chunk in my_file.chunks():
        #     f.write(chunk)
        # f.close()
        with open(uploadroot + '/' + str(my_file.name).replace('"',''), 'wb') as f:
            for chunk in my_file.chunks():
                f.write(chunk)
            f.close()
        print('上传成功')

        # 返回文件名
        # return HttpResponse(json.dumps({'filename': my_file.name}, ensure_ascii=False), content_type='application/json')
        # return HttpResponse(json.dumps({'res': 200}))
        # return redirect('http://127.0.0.1:8080?image_name=' + my_file.name.split('.')[0])
        return Response({'filename': my_file.name.split('.')[0],'filetype':my_file.name.split('.')[1]})


# 七牛云密钥接口
from qiniu import Auth
class QiNiu(APIView):
    
    def get(self, request):
        
        # 圣光明一个密钥对象
        q = Auth('FrZcNsgzftewSOxOugEoFgQq93VQhHDv_UMAJ0P2','30fYKbfMJEHaa9iBgvWHK0JdUyX_CMEtelS_RwXx')
        # 生成令牌
        token = q.upload_token('my-data-for-fcg',expires=30000)
        
        return Response({'uptoken':token})
    
# 修改用户头像
class UpdateUser(APIView):
    
    def get(self, request):
        uid = request.GET.get('uid')
        img = request.GET.get('img')
        user = User.objects.filter(id=uid).first()
        user.img = img
        user.save()
        print(User.objects.filter(id=uid).first().img)
        return Response({'code': 200,'message': '修改成功','img_name':user.img.split('.')[0], 'img_type':user.img.split('.')[1]})
    
# 获取用户头像
class UserImg(APIView):
    def get(self, request):
        uid = request.GET.get('uid')
        user = User.objects.filter(id=uid).first()
        return Response({'code': 200,'message': '请求成功','img':user.img,'type': user.type})
# 修改用户密码
class Password(APIView):
    def get(self, request):
        uid = request.GET.get('uid')
        password = request.GET.get('password')
        user = User.objects.filter(id=uid).first()
        user.password = password
        user.save()
        return Response({'code': 200,'message': '修改成功'})
# 装饰器
def my_decorator(func):
    def wrapper(request, *args, **kwargs):
        print('这个装饰器被调用')
        print('请求接口地址是%s'% request.path)
        return func(request, *args, **kwargs)    
    return wrapper
# 类装饰器调用
from django.utils.decorators import method_decorator

# 获取用户数据
class UserInfo(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    @method_decorator(my_decorator)
    def list(self, request, *args, **kwargs):
        uid = request.GET.get('uid')
        queryset = User.objects.filter(id=uid)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
# 展示商品列表
class GoodsInfo(ModelViewSet):
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    
    
# 商品入库接口

class GoodsCreate(APIView):
    def get(self, request, *args, **kwargs):
        name = request.GET.get('name')
        desc = request.GET.get('desc')
        img = request.GET.get('img')
        video = request.GET.get('video')
        param = request.GET.get('param')
        cid = request.GET.get('cid')
        price = request.GET.get('price')
        
        goods = Goods.objects.filter(name=name)
        if goods:
            return Response({'code':301,'message': '该商品已存在'})
        good = Goods(
            name=name,
            desc=desc,
            img=img,
            video=video,
            param=param,
            cid=cid,
            price=price)
        good.save()
        return Response({'code':200,'message': '创建成功'})
     
# 展示分类列表
class CategoryInfo(ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    
    
# 商品分类接口

class CategoryCreate(APIView):
    def get(self, request, *args, **kwargs):
        cname = request.GET.get('cname')
        
        cates = Category.objects.filter(cname=cname)
        if cates:
            return Response({'code':301,'message': '该分类已存在'})
        cate = Category(
            cname=cname)
        cate.save()
        return Response({'code':200,'message': '创建成功'})   
    
# 获取单个分类
class CateShow(APIView):
    def get(self, request):
        cid = request.GET.get('cid')
        cate = Category.objects.filter(id=cid).first()
        print(cate.cname)
        return Response({'code':200,'message': '创建成功','cid':cate.id,'cname':cate.cname})   
# 修改用户权限等级
class UpUserType(APIView):
    def get(self, request):
        uid = request.GET.get('uid')
        type = request.GET.get('type')
        user = User.objects.filter(id=uid).first()
        user.type = type
        user.save()
        print(user.type)
        return Response({'code':200,'message': '创建成功','uid':user.id,'type':user.type})  
        # return Response({'code':200,'message': '创建成功'})   
       
        
        
        
from django.utils.deprecation import MiddlewareMixin

# 定义中间件类
class MyMiddleWare(MiddlewareMixin):
    # 请求之前
    def process_request(self, request):
        # pass
        uid = request.GET.get('uid')
        # print(uid)
        jwt_str = request.GET.get('jwt', None)
        print(jwt_str)
        decode_jwt = jwt.decode(jwt_str, '446652', algorithms=['HS256'])
        if str(decode_jwt['uid']) != str(uid):
            return HttpResponse('你篡改了用户id')
        pass
    # 模板渲染之前
    def process_view(self, request, view_func,view_args,view_kwargs):
        pass
    # 请求之后
    def process_response(self, request, response):
        return response
    